package com.shimao.celnet.payment.controller.api;

import com.baiwang.bop.client.BopException;
import com.baiwang.bop.client.IBopClient;
import com.baiwang.bop.request.impl.bizinfo.SearchRequest;
import com.baiwang.bop.respose.entity.bizinfo.Recommendation;
import com.baiwang.bop.respose.entity.bizinfo.SearchResponse;
import com.shimao.celnet.payment.form.BGoodsCodeForm;
import com.shimao.celnet.payment.model.BCtaxGoodsCode;
import com.shimao.celnet.payment.model.BGoodsCode;
import com.shimao.celnet.payment.model.request.CallIn_InvoiceGoodsRequest;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.BCtaxGoodsCodeService;
import com.shimao.celnet.payment.service.BGoodsCodeService;
import com.shimao.celnet.payment.service.apiservice.CallOut_invOpenOutService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 *  外部系统 → 世茂支付平台；   【数据】：商品名信息；
 *  christ
 *  2018/01/11
 */
@RestController
@RequestMapping(value = "/invoice")
public class CallIn_outGoodsUpInController {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private BGoodsCodeService bGoodsCodeService;

    @Autowired
    private CallOut_invOpenOutService invOpenOutService;

    @Autowired
    private BCtaxGoodsCodeService bCtaxGoodsCodeService;

    @RequestMapping(value = "/goods", method = RequestMethod.POST)
    public Object goodsUpIn(@RequestBody @Valid CallIn_InvoiceGoodsRequest callIn_invoiceGoodsRequest,BindingResult result){
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        //验证参数
        String goodsName = callIn_invoiceGoodsRequest.getGoodsName();
        //界面输入验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                logger.debug("缺少必要参数：" + error.getDefaultMessage());
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }
        BGoodsCodeForm formBean = new BGoodsCodeForm();
        formBean.setGoodsName(goodsName);
        formBean = bGoodsCodeService.getGoodsInfo(goodsName);
        if(formBean != null && formBean.getCtaxGoodsCode() != null){
            //根据提交的商品名查询数据，如果数据库存在则立即返回
            retJson.addBody("goodsName",formBean.getGoodsName());//自定义商品名称
            retJson.addBody("ctaxGoodsCode",formBean.getCtaxGoodsCode());//国税商品编码
            retJson.addBody("goodsCode",formBean.getCtaxGoodsCode());//自定义商品编码
        }else{
            //调用支付平台到百望的查询商品编码接口
            SearchRequest request = new SearchRequest();
            request.setCommodityName(goodsName);
            /**
             * {name='小米手机', recommendations=[
             * Recommendation{code='1090505010000000000', parentName='移动通信手持机（手机）',desc='车载终端、无线固定话机等终端按照技术标准对应到下列细目中，包括GSM手持机、CDMA手持机、3G手持机、SCDMA终端', prob='93.30%'},
             * Recommendation{code='1090509010000000000', parentName='电子计算机整机', desc='指数字式自动数据处理设备，含模拟式或混合式自动数据处理设备，包括计算机工作站、微型计算机设备、服务器、系统形式自动数据处理设备', prob='5.05%'},
             * Recommendation{code='1090509020000000000', parentName='计算机数字式处理部件', desc='包括高性能计算机数字式处理部件、微型计算机数字式处理部件、服务器数字式处理部件、笔记本计算机数字式处理部件、工业控制计算机处理部件、工业控制计算机输入输出部件、其他计算机数字式处理部件', prob='1.42%'}]}
             */
            try{
                //同步请求获取token
                String token = invOpenOutService.getToken();
                float maxProb = 0;//最大使用频率
                float prob = 0;//使用频率
                IBopClient client = invOpenOutService.getClient();
                SearchResponse response = client.execute(request, token, SearchResponse.class);
                List<Recommendation> geDatatList =  response.getRecommendations();
                BCtaxGoodsCode ctaxBean = new BCtaxGoodsCode();
                for(Recommendation recommendations : geDatatList){
                    prob=Float.valueOf(recommendations.getProb().replace("%",""));
                    if(prob>maxProb){//使用比例最大的国税商品编码保存
                        maxProb= prob;
                        //国税商品编码
                        ctaxBean.setCtaxGoodsCode(recommendations.getCode());
                        //国税商品名称
                        ctaxBean.setCtaxGoodsName(recommendations.getParentName());
                        //国税商品说明
                        ctaxBean.setRemark(recommendations.getDesc());
                    }

                }
                //存储国税编码数据
                bCtaxGoodsCodeService.saveUpdate(ctaxBean);
                //存储自定义编码数据
                BGoodsCode bGoodsCode = new BGoodsCode();
                bGoodsCode.setGoodsName(goodsName);//自定义商品名称
                bGoodsCode.setCtaxGoodsCode(ctaxBean.getCtaxGoodsCode());//国税商品编码
                String goodsCode = bGoodsCodeService.saveUpdate(bGoodsCode);
                //返回数据
                retJson.addBody("goodsName",bGoodsCode.getGoodsName());//自定义商品名称
                retJson.addBody("ctaxGoodsCode",ctaxBean.getCtaxGoodsCode());//国税商品编码
                retJson.addBody("goodsCode",goodsCode);//自定义商品编码

            } catch ( BopException e){
                logger.info("error"+e.getSubMessage());
                retJson.setErrorCode(e.getErrCode());
                retJson.setErrorMessage(e.getSubMessage());
                return retJson.toString();
            }
        }
        return retJson.toString();
    }
}
